package com.data.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@SuppressWarnings("ALL")
public class HttpClientUtil {

  public static String doGet(String url, Map<String, String> param) {

    // 创建Httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String resultString = "";
    CloseableHttpResponse response = null;
    try {
      // 创建uri
      URIBuilder builder = new URIBuilder(url);
      if (param != null) {
        for (String key : param.keySet()) {
          builder.addParameter(key, param.get(key));
        }
      }
      URI uri = builder.build();

      // 创建http GET请求
      HttpGet httpGet = new HttpGet(uri);

      // 执行请求
      response = httpclient.execute(httpGet);
      // 判断返回状态是否为200
      if (response.getStatusLine().getStatusCode() == 200) {
        resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (response != null) {
          response.close();
        }
        httpclient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return resultString;
  }

    public static String doGetToken(String url, Map<String, String> param,String accessToken) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Admin-Token",accessToken);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

  public static String doGet(String url) {
    return doGet(url, null);
  }



  public static String doPost(String url) {
    return doPost(url, null);
  }

  public static String doPostJson(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Post请求
      HttpPost httpPost = new HttpPost(url);
      // 创建请求内容
      StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
      httpPost.setEntity(entity);
      // 执行http请求
      response = httpClient.execute(httpPost);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return resultString;
  }

  public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException {
    String body = "";

    //创建httpclient对象
    CloseableHttpClient client = HttpClients.createDefault();
    //创建post方式请求对象
    HttpPost httpPost = new HttpPost(url);

    //装填参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if(map!=null){
      for (Entry<String, String> entry : map.entrySet()) {
        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
    }
    //设置参数到请求对象中
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

    System.out.println("请求地址："+url);
    System.out.println("请求参数："+nvps.toString());

    //设置header信息
    //指定报文头【Content-type】、【User-Agent】
    httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
    httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

    //执行请求操作，并拿到结果（同步阻塞）
    CloseableHttpResponse response = client.execute(httpPost);
    //获取结果实体
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      //按指定编码转换结果实体为String类型
      body = EntityUtils.toString(entity, encoding);
    }
    EntityUtils.consume(entity);
    //释放链接
    response.close();
    return body;
  }


  /**
   * post请求
   * @param url         url地址
   * @param jsonParam     参数
   * @param noNeedResponse    不需要返回结果
   * @return
   */
  public static String  httpPostStr(String url, JSONObject jsonParam, boolean noNeedResponse){
    //post请求返回结果
    HttpClient httpClient = HttpClientBuilder.create().build();
    String res = "";
    HttpPost method = new HttpPost(url);
    method.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
    try {
      if (null != jsonParam) {
        //解决中文乱码问题
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        method.setEntity(entity);
      }
      HttpResponse result = httpClient.execute(method);

      url = URLDecoder.decode(url, "UTF-8");
      /**请求发送成功，并得到响应**/
      if (result.getStatusLine().getStatusCode() == 200) {
        String str = "";
        try {
          /**读取服务器返回过来的json字符串数据**/
          str = EntityUtils.toString(result.getEntity());
          if (noNeedResponse) {
            return res;
          }
          res = str;
        } catch (Exception e) {
        }
      }
    } catch (IOException e) {
    }
    return res;
  }

  public static String post(String requestUrl, String accessToken, String params)
          throws Exception {
    String contentType = "application/x-www-form-urlencoded";
    return post(requestUrl, accessToken, contentType, params);
  }
  public static String post(String requestUrl, String accessToken, String contentType, String params)
          throws Exception {
    String encoding = "UTF-8";
    if (requestUrl.contains("nlp")) {
      encoding = "GBK";
    }
    return post(requestUrl, accessToken, contentType, params, encoding);
  }
  public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
          throws Exception {
    String url = requestUrl + "?access_token=" + accessToken;
    return postGeneralUrl(url, contentType, params, encoding);
  }

  public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
          throws Exception {
    URL url = new URL(generalUrl);
    // 打开和URL之间的连接
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    // 设置通用的请求属性
    connection.setRequestProperty("Content-Type", contentType);
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoInput(true);

    // 得到请求的输出流对象
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.write(params.getBytes(encoding));
    out.flush();
    out.close();

    // 建立实际的连接
    connection.connect();
    // 获取所有响应头字段
    Map<String, List<String>> headers = connection.getHeaderFields();
    // 遍历所有的响应头字段
    for (String key : headers.keySet()) {
      System.err.println(key + "--->" + headers.get(key));
    }
    // 定义 BufferedReader输入流来读取URL的响应
    BufferedReader in = null;
    in = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), encoding));
    String result = "";
    String getLine;
    while ((getLine = in.readLine()) != null) {
      result += getLine;
    }
    in.close();
    System.err.println("result:" + result);
    return result;
  }




    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, HashMap<String,String> heads) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (heads != null) {
                for (String key : heads.keySet()) {
                    conn.setRequestProperty (key,heads.get(key));
                }
            }

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            if (param != null) {
                out.print(param);
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader (conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }








    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, HashMap<String,String> heads) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (heads != null) {
                for (String key : heads.keySet()) {
                    conn.setRequestProperty (key,heads.get(key));
                }
            }

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            if (param != null) {
                out.print(param);
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader (conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 Get 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair (key, param.get(key)));
                }
                // 模拟表单
//                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");

                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }


    public static String doPostMap(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair (key, String.valueOf (param.get(key))));
                }
                // 模拟表单
//                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");

                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }
}
